<?php
namespace app\api\controller;
use app\common\BaseController;
use app\api\model\Ticket as TicketModel;
use app\common\Logs;
use think\Db;
class Ticket extends BaseController{    
    public function __construct(TicketModel $model){
        parent::__construct();
        $this->model = $model;
    }
    public function allList(){
        $params = $this->request->param();
        if(empty($params['type_id'])){
            return '缺少type_id参数';
        }        
        $tickets = [];
        $types = $this->model->where("type_id",$params["type_id"])->select();
        foreach($types as $item){
            for($i = $item["start_num"];$i<=$item["end_num"];$i++){
                array_push($tickets,array('id'=>$item['id'],'no'=>$item["prefix"] . $i));
            }   
        }
        
        $selects = []; 
        $datas = Db::name("single")->where("type_ticket",$params['type_id'])->column('ticket_num'); 
        foreach($datas as $item){    
            $selects=array_merge($selects,json_decode($item,true));
        }
        $arr=[];
        foreach($tickets as $key => $item){
            if(!in_array($item,$selects)){
               array_push($arr,$item);
            }
        }     
        return $arr;
    }

    public function index(){
        $params = $this->request->param();      
        if(!empty($params['userId'])){
            $params['operator_id'] = $params['userId'];
        }
        $data = $this->model->ticketList($params);
        return $data; 
    }
    //添加
    public function create(){        
        $param = $this->request->param();       
        $params = json_decode($param['params'],true);        
        $operator_id = json_decode($param['operator_id'],true);
        if(empty($params['type_id'])){
            return '缺少type_id参数';
        }
        $params['total_num'] = $params['end_num'] - $params['start_num'] + 1;
        $data = $this->model->allowField(true)->isUpdate(false)->data($params)->save();
        if($data){
            Logs::add("新增现票记录",$operator_id,"现票", null,json_encode($this->model,JSON_UNESCAPED_UNICODE));    
        }
        return $this->model;
    }
    //编辑
    public function update(){        
        $param = $this->request->param();  
        $params = json_decode($param['params'],true);        
        $operator_id = json_decode($param['operator_id'],true);
        $old = $this->model->where("id",$params['id'])->find();
        $data = $this->model->allowField(true)->isUpdate(true)->save($params,['id',$params['id']]);
        if($data){
            Logs::add("修改现票记录",$operator_id,"现票", json_encode($old,JSON_UNESCAPED_UNICODE),json_encode($this->model,JSON_UNESCAPED_UNICODE));    
        }
        return $this->model;
    }
    //删除
    public function delete(){
        $params = $this->request->param();  
        $old = $this->model->where("id",$params['id'])->find();       
        $data = $this->model->allowField(true)->where('id',$params['id'])->delete();
        if($data){
            Logs::add("删除现票记录",$params['operator_id'],"现票", json_encode($old,JSON_UNESCAPED_UNICODE),json_encode($this->model,JSON_UNESCAPED_UNICODE));    
        }
        return $data;
    }

    public function csv(){
       
        $title = array('票号');
        include(EXTEND_PATH.'phpexcel/PHPExcel.php'); 
        $obj = new \PHPExcel();      
        $obj->getActiveSheet()->getColumnDimension('A')->setWidth(18);        
        //横向单元格标识      
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');  
        $obj->getActiveSheet(0)->setTitle('sheet名称');   //设置sheet名称      
        $_row = 1;   //设置纵向单元格标识      
        if($title){      
            $_cnt = count($title);    
            $i = 0;      
            foreach($title AS $v){   //设置列标题      
                $obj->setActiveSheetIndex(0)->setCellValue($cellName[$i].$_row, $v);      
                $i++;      
            }      
            $_row++;      
        }      

        $params = $this->request->param();
        //type,1：团队，2：散拼，3：项目
        if(!empty($params['type_id'])){
            $where['type_id'] = $params['type_id'];               
        }       
        $tickets = [];
        $types = $this->model->where($where)->select();
        foreach($types as $item){
            for($i = $item["start_num"];$i<=$item["end_num"];$i++){
                array_push($tickets,array('id'=>$item['id'],'no'=>$item["prefix"] . $i));
            }   
        }
        
        $selects = []; 
        $datas = Db::name("single")->where("type_ticket",$params['type_id'])->column('ticket_num'); 
        foreach($datas as $item){    
            $selects=array_merge($selects,json_decode($item,true));
        }
        $arr=[];
        foreach($tickets as $key => $item){
            if(!in_array($item,$selects)){
               array_push($arr,$item);
            }
        }  
       
        //填写数据      
        if($arr){      
            $i = 0;      
            foreach($arr AS $_v){                
                $obj->getActiveSheet(0)->setCellValueExplicit($cellName[0] . ($i+$_row), $_v['no'],\PHPExcel_Cell_DataType::TYPE_STRING);                                
                $i++;      
            }      
        }  
        //文件名处理      
        
        $fileName = uniqid(time(),true);      
        
        $objWrite = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');  
        $isDown=true;
        if($isDown){   //网页下载      
            header('pragma:public');      
            header("Content-Disposition:attachment;filename=$fileName.xls");      
            $objWrite->save('php://output');exit;      
        }      
        $_fileName = iconv("utf-8", "gb2312", $fileName);   //转码      
        $_savePath = $savePath.$_fileName.'.xlsx';      
         $objWrite->save($_savePath);  
         return $savePath.$fileName.'.xlsx';    
    }

}